import { Guid } from './../common/utils/guid';
export class SyncWriterServices {
    actionTimer: NodeJS.Timeout;
    actionHandlers: { key: string; handle: () => Promise<void>; }[] = [];
    static Current: SyncWriterServices = new SyncWriterServices();

    constructor() {
        this.StartTimer();
    }

    private StartTimer() {
        if (!this.actionTimer) {
            this.actionTimer = setInterval(this.ActionTimerHandler.bind(this), 1000);
        }
    }

    private StopTimer() {
        clearInterval(this.actionTimer);
        this.actionTimer = null;
    }

    private async ActionTimerHandler() {
        this.StopTimer();
        try {
            for (let item of this.actionHandlers) {
                try {
                    let ts = Date.now();
                    await item.handle();
                    console.log(item.key, "异步函数执行成功, 耗时：", Date.now() - ts, "毫秒");
                } catch (error) {
                    console.error(item.key, "异步函数执行失败， 丢弃！",error);
                }
            }

        } catch (error) {
            console.error(error);
        }
        finally {
            this.actionHandlers = [];
            this.StartTimer();
        }
    }

    AddHandler(handler) {
        this.actionHandlers.push({
            key: Guid.GetGuid(),
            handle: handler,
        });
    }
}